package com.zhengshang.security.service;

import com.zhengshang.common.constant.UserConstants;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.enums.UserStatus;
import com.zhengshang.common.exception.BaseException;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService appUserService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名去数据库查询
        SysUser appUser = appUserService.selectUserByUserName(username);

        if (StringUtils.isNull(appUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(appUser.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(appUser.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        } else if (!UserConstants.USER_TYPE_APP.equals(appUser.getUserType())) {
            log.info("登录用户：{} 非移动端用户无法登录APP.", username);
            throw new BaseException("对不起，您的账号：" + username + " 不是移动端用户，无法登录APP");
        }

        return createLoginUser(appUser);
    }

    public UserDetails createLoginUser(SysUser appUser) {
        return new LoginAppUser(appUser, permissionService.getMenuPermission(appUser));
    }
}
